package com.jdfarm.tiandimap

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.webkit.WebChromeClient
import android.webkit.WebView
import com.jdfarm.common.MapControl
import com.jdfarm.common.OnMapLoadComplete
import com.jdfarm.jsBridge.JsFun

class MapView @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0,
) : WebView(context, attrs, defStyleAttr), MapControl {

    init {
        initParam()
        loadUrl("file:///android_asset/map.html")
    }

    /**
     * 初始化操作
     */
    @SuppressLint("SetJavaScriptEnabled")
    private fun initParam() {
        settings.apply {
            domStorageEnabled = true
            mixedContentMode = 0
            allowFileAccess = false
            javaScriptEnabled = true
            loadWithOverviewMode = true
            useWideViewPort = true
            webChromeClient = object : WebChromeClient() {

            }
        }
        //添加js调用native的对象
        addJavascriptInterface(JsFun(this), "JsFun")
    }

    /**
     * 地图加载完成监听
     */
    override var onMapLoadComplete: OnMapLoadComplete = object : OnMapLoadComplete {
        override fun onComplete() {
            Log.d("加载完成", "地图加载完成回调")
        }
    }


    /**
     * 放大
     */
    override fun zoomToLarge() {
        post { loadUrl("javascript:zoomToLarge()") }
    }

    /**
     * 缩小
     */
    override fun zoomToSmall() {
        post { loadUrl("javascript:zoomToSmall()") }
    }

    /**
     * 放大缩小到固定级别
     */
    override fun zoomTo(zoomLevel: Int) {
        post { loadUrl("javascript:zoomToSmall($zoomLevel)") }
    }

    /**
     * 添加加载监听
     */
    override fun setOnMapLoadListener(onMapLoadComplete: OnMapLoadComplete) {
        this.onMapLoadComplete = onMapLoadComplete
    }

}